//
//  NetWorkTools.swift
//  新浪微博
//
//  Created by 李赛 on 15/5/18.
//  Copyright (c) 2015年 李赛. All rights reserved.
//

import UIKit
import Alamofire
import SVProgressHUD

class NetWorkTools: NSObject {

    class func requestJSON (method: Alamofire.Method, URLString: String, parameters: [String : AnyObject]? = nil, completion:(json:AnyObject?) -> ()) {
        Alamofire.request(method, URLString, parameters: parameters).responseJSON() { (_, _, json, error) -> Void in
            if json == nil || error != nil {
                SVProgressHUD.showInfoWithStatus("网络不给力啊")
                
                completion(json: nil)
                return
            }
            completion(json: json)
        }
    }
    
    static let boundary = "stackLi-upload"
    
    class func uploadPicture(URLString: String, fieldName: String, dataList: [String : NSData!], parameters: [String: AnyObject]? = nil ) {
    
        var request = NSMutableURLRequest(URL: NSURL(string: URLString)!)
        // 设置请求的方法
        request.HTTPMethod = "POST"
        // 设置content-type
        let type = "multipart/form-data; boundary=\(boundary)"
        request.setValue(type, forHTTPHeaderField: "Content-Type")
        
//        let data = formFata
    }
    
    // 生成上传数据文件
    private class func formData(fieldName: String , dataList: [String: NSData!], parameters: [String: AnyObject]? = nil) -> NSData{
        var dataM = NSMutableData()
        
        // 遍历字典 拼接字符串参数
        if let params = parameters {
            for (k,v) in params {
                var strM = "--\(boundary)\r\n"
                strM += "Content-Disposition: form-data; name=\"\(k)\"\r\n\r\n"
                strM += "\(v)\r\n"
                
                dataM.appendData(strM.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
            }
        }
        
        // 遍历文件属性数组
        for (k,v) in dataList {
            var strM = "--\(boundary)\r\n"
            strM += "Content-Disposition: form-data; name=\"\(fieldName)\"; filename=\"\(k)\"\r\n"
            strM += "Content-Type: application/octet-stream\r\n\r\n"
            
            dataM.appendData(strM.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
            dataM.appendData(v)
            dataM.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
        }
        // 请求结尾字符串 告诉服务器 上传数据已经结束
        let tail = "--\(boundary)--\r\n"
        dataM.appendData(tail.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
        return dataM
    }
    
}
